package com.superiron.scaffold.config;

import com.superiron.scaffold.security.component.DynamicSecurityService;
import com.superiron.scaffold.security.service.GlobalUserDetailsService;
import com.superiron.scaffold.service.MenuRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * mall-security模块相关配置
 * Created by macro on 2019/11/9.
 */
@Configuration
public class WebSecurityConfig {

    @Autowired
    private GlobalUserDetailsService globalUserDetailsService;
	@Autowired
	private MenuRoleService menuRoleService;
	@Autowired
	private RedisTemplate redisTemplate;

    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> globalUserDetailsService.loadUserByUsername(username);
    }
	
    @Bean
    public DynamicSecurityService dynamicSecurityService() {
        return new DynamicSecurityService(){
	
			/**
			 * 加载资源ANT通配符和资源对应MAP
			 */
			@Override
			public void loadDataSource() {
				List<Map<String, Object>> resourceList = menuRoleService.queryMenuRoleList();
				Map<String, String> tmpMap = Optional.ofNullable(resourceList).get().stream()
						.collect(Collectors.groupingBy(entity -> (String) entity.get("path"),
								Collectors.mapping(entity -> (String) entity.get("role_code"), Collectors.joining(","))));
				
				redisTemplate.opsForValue().set(rolePrefix, tmpMap);
			}
		};
    }
}
